<?php


namespace app\reimburse\admin;


use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\project\model\Category;
use app\project\model\Config;
use app\reimburse\model\Project;
use app\project\model\ProjectUuid;
use app\user\model\User;

class Index extends Admin
{
    protected $user;
    protected $where = true;
    public function initialize()
    {
        parent::initialize();
        $this->user = session('user_auth');
        if ($this->user['role']==2){
            $this->where = ['principal'=>UID];
        }elseif ($this->user['role']==3){
            $this->where = ['team'=>UID];
        }
        $this->model = new Project();
    }

    public function index(){
        $map = $this->getMap();
        if ($map){
            foreach ($map as &$value){
                if ($value[0] == 'principal_name'){
                    $info = User::where('username', '=', $value[2])->find();
                    $value[0]='principal';
                    $value[2]=$info['id'];
                }elseif ($value[0] == 'team_name'){
                    $info = User::where('username', '=', $value[2])->find();
                    $value[0]='team';
                    $value[2]=$info['id'];
                }
            }
        }
        $data = $this->model->with(['principalUser','teamUser','category'])->where($map)->where($this->where)->select();
        if ($this->request->param('execl')){
            $cellName = [
                ['id', 'auto', 'ID'],
                ['name', 'auto', '姓名'],
                ['staff_number', 'auto', '工号'],
                ['project_title', 'auto', '所属项目'],
                ['type_name', 'auto', '报销单类别'],
                ['team_name', 'auto', '团队负责人'],
                ['principal_name', 'auto', '项目负责人'],
                ['setting_name', 'auto', '申请类别'],
                ['money', 'auto', '申请资金'],
                ['status_name', 'auto', '当前状态'],
                ['create_time', 'auto', '创建时间'],
                ['update_time', 'auto', '更新时间'],
                ['cause', 'auto', '事由'],
            ];
            return plugin_action('Excel/Excel/export', ['test', $cellName, $data]);
        }
        $btn_execl = [
            'title' => '导出',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-primary js-get',
            'href'  => url('',['execl'=>'9'])
        ];

        $btn_del = [
            'title' => '删除',
            'icon'  => 'fa fa-times',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href'  => url('del', ['id' => '__id__']),
            'data-title'=>'真的要删除吗?'
        ];
        $show_one = [
            'title'=>'待审核',
            'icon'=>'fa fa-fw fa-eye',
            'href'=>url('status',['id'=>'__id__']),
        ];


        return ZBuilder::make('table')
            ->addColumns([
                ['project_uuid', '项目号'],
                ['project_title', '项目名'],
                ['category_name', '项目分类'],
                ['principal_name', '项目负责人'],
                ['team_name', '团队负责人'],
                ['type', '类别',['教学','科研','人才经费']],
                ['money', '金额'],
                ['status', '审核状态', 'status','',['待负责人审核:info','待总负责人审核:primary','已通过:success']],
                ['create_time', '申请时间', 'datetime',],
                ['update_time', '最后审核时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add', [])//,true
            ->addTopButton('execl', $btn_execl)
            ->addRightButton('del',$btn_del)
            ->addRightButton('show',$show_one)//,true
            ->setRowList($data)
            ->setSearchArea([
                ['daterange', 'create_time', '申请时间'],
                ['daterange', 'end_time', '审核时间'],
                ['text', 'principal_name', '项目负责人'],
                ['text', 'team_name', '团队负责人'],
                ['select', 'category_id', '项目分类','','',Category::where('pid','<>',0)->column('id,title')],
            ])
            ->fetch();
    }


    public function add()
    {
        if($this->request->isPost()){
            $data = $this->request->post('', null, 'trim');
//            dump($data);die;
            $result = $this->validate($data, 'Project');
            if (true !== $result) {
                $this->error($result);
            }
//            $cate = Category::where('team',6)->find($data['category_id']);
            $cate = Category::where('team',UID)->find($data['category_id']);
            if (empty($cate)){
                $this->error('你不能申请当前项目');
            }
            $cate = json_decode($cate,true);
//            dump($cate);die;
            $error = '当前项目没有此项报销';
            foreach ($cate['setting']['shengyu'] as $value){
//                if (isset($data[$value['key']])&&$data[$value['key']]!=0){//分类有的类别,且传了上来
//                    if($data['money']*$data[$value['key']]/100>$value['value']*$cate['money']/100){//这里需要判断传上来的比例算出是否大于分类剩余的比例
//                        $error = $value['title'].'最高只能报销项目的'.$value['value'].'%即'.$value['value']*$cate['money']/100 . '万元';
//                    }
//                    $value['value'] = $data[$value['key']];
//                    $json[] = $value;
//                }
                if ($value['key']==$data['setting_type']){//
                    if ($data['money']<=$cate['money'] * $value['value']/100){
                        $error = true;
                        $data['setting_name'] = $value['title'];
                    }else{
                        $error = $value['title'].'最高只能报销'.$value['value'].'%即'.($cate['money'] * $value['value']).'万元,您已超额';
                    }
                }
            }
            if ($error!==true){
                $this->error($error);
            }
            $data['principal'] = $cate['principal'];
            $data['team'] = $cate['team'];
            $data['project_title'] = $cate['title'];
//            $data['start_time'] = strtotime($data['start_time']);
//            $data['end_time'] = strtotime($data['end_time']);
            $data['create_time'] = time();

            if ($info = $this->model->create($data)){
                $details = UID . '操作project_add,id为' . $info['id'];
                action_log('project_add', 'project', $info['id'], UID, $details);
                $this->success('新增成功','index',['_parent_reload'=>1,'_close_pop'=>1]);
            }
            $this->error('新增失败');
        }
        $config = Config::column('title','key');

        $jichu = [
            ['text', 'name', '姓名','请输入自己姓名'],
            ['text', 'staff_number', '职工号','请输入自己的职工号'],
//            ['text', 'project_title', '项目名','项目名称请输入全程'],
            ['select', 'project_uuid', '项目号','请选择项目的项目号',ProjectUuid::column('project_uuid'),''],
            ['select', 'category_id', '分类','请选择项目分类',Category::column('id,title')],
//            ['select', 'principal', '项目负责人', '请选择当前项目负责人', User::where('role', '=', 2)->column('id,username')],
//            ['select', 'team', '团队负责人', '请选择当前项目负责人', User::where('role', '=', 3)->column('id,username'),UID],
            ['radio', 'type', '类别', '请选择当前项目类别',['教学','科研','人才经费等']],
            ['textarea', 'cause', '事由', '请说明项目事由'],
        ];
        $zijin = [
            ['select', 'setting_type', '报销类别', '<span class="text-danger">填写此次申报的类别</span>',$config],
            ['number', 'money', '金额(万元)', '<span class="text-danger">填写此次申报的金额</span>'],
        ];
//        $config = Config::select();
//        foreach ($config as $value){
//            $zijin[] = ['number',$value['key'],$value['title'],'没有的不填写,最多配置'.$value['value'].',即:'.$value['value'].'%',0];
//        }

        return ZBuilder::make('form')
            ->setPageTips('报销单一旦提交后无法修改,请仔细填写','danger')
            ->addFormItems([
                [
                    'type' => 'group',
                    'options' => [
                        '基本信息'=>$jichu,
                        '资金信息'=>$zijin
                    ]
                ]
            ])
            ->submitConfirm()
            ->fetch();
    }

    /**
     * 这里需要分辨有什么权限
     * @param int $id
     * @return mixed
     * @throws \think\Exception
     */
    public function status($id = 0)
    {

        $info = $this->model->with(['principalUser','teamUser','category'])->find($id);
        if (!$info){
            $this->error('数据不存在');
        }

        if($this->request->isPost()){
            if ($info['status']==0){//需要项目人负责人审核
                $update = [
                    'status'=>1,
                    'update_time'=>time()
                ];
            }elseif($info['status']==1&&$this->user['role']==1){//需要超管审核
                $update = [
                    'status'=>2,
                    'update_time'=>time()
                ];
                $cate = json_decode(Category::where('id',$info['category_id'])->find(),true);
                foreach ($cate['setting']['shengyu'] as &$value){
                    if ($value['key']==$info['setting_type']){
                        if ($cate['money'] * $value['value'] / 100 - $info['money']){
                            $value['value'] -= $info['money']/$cate['money']*100;
                        }else{
                            $this->error('该项目申请资金已超剩下可以申请资金额度');
                        }
                    }
                }
                Category::where('id',$cate['id'])->update(['setting'=>json_encode($cate['setting'])]);
            }elseif($info['status']==2){
                $this->error('无需审核');
            }else{
                $this->error('权限不足');
            }
            if ($info->save($update)){
                $details = UID . '操作project_status,id为' . $info['id'];
                action_log('project_status', 'project', $info['id'], UID, $details);
                $this->success('审核通过','index',['_parent_reload'=>1,'_close_pop'=>1]);
            }
            $this->error('审核失败');
        }
//        $table_inside = [];
//        $table_inside[] = ['类别', '比例(%)', '金额(万元)'];
//        $info = json_decode($info,true);
//        dump($info);die;
//        foreach ($info['setting'] as $key=>$value){
//            $table_inside[] = [$value['title'],$value['value'],round($info['money']*$value['value']/100,2)];
//        }
//        $table_inside[] = '4:1';       // 最后一个为字符串，用来设置所在单元格的合并，如果不需要合并则无需填写。
//        $table_data = [
//            ['报销单名:'.$info['project_title'],'报销编号:'.$info['project_uuid'], '团队负责人(申请人):'.$info['team_name'], '项目负责人:'.$info['principal_name']],
//            ['项目:'.$info['category_name'], '当前状态:'.$info['status_name'], '提交时间:'.date('Y年m月d日',$info['create_time']), '最后一次审核时间:'.date('Y年m月d日',$info['create_time'])],
//            ['申请资金:'.$info['money'].'万元', '申请类别:'.$info['status_name']],
//            ['事由[:2]',$info['cause'].'[4:2]',],
//        ];
        $table_data = [
            ['姓名', $info['name'], '工号', $info['staff_number'], '属于项目', $info['project_title']],
            ['报销单类别', $info['type_name'],'团队负责人(申请人)',$info['team_name'], '项目负责人',$info['principal_name']],
            ['申请类别',$info['setting_name'].'','申请资金',$info['money'].'万元','当前状态:',$info['status_name']],
            ['申请资金:',$info['money'].'万元','提交时间:',date('Y年m月d日',$info['create_time']),'最后一次审核时间:',date('Y年m月d日',$info['update_time'])],
            ['此报销单主要事由<br>列举出来（5项以内）[2]', $info['cause'].'[4]'],
        ];



        return ZBuilder::make('form')
            ->setPageTips('该页面用于审核和信息展示,审核可操作审核按钮')
            ->addFormItems([ // 批量添加表单项
                ['complexTable', 'list_user', '客户列表', $table_data]
            ])
            ->setBtnTitle('submit', '通过')
            ->hideBtn(['back'])
            ->addHidden('submit')
            ->submitConfirm()
            ->fetch();
    }


    /**
     * 这里删除只能删除未审核的，且为本人提交的，所以不存在批量删除
     * 这里需要验证状态
     * @param int $id
     */
    public function del($id = 0)
    {
        $info = $this->model->find($id);
        if (!$info){
            $this->error('数据不存在');
        }
        $this->role($info);
        if ($info['status']!=0){
            $this->error('只有未审核的项目才可删除');
        }
        $this->model->destroy($id);
        $this->success('删除成功');
    }

    /**
     * 验证权限
     * @param $info当前操作数据
     */
    protected function role($info){
        if ($this->user['role']==2&&$this->user['uid']!=$info['principal']){
            $this->error('该操作权限不够');
        }
        if ($this->user['role']==3&&$this->user['uid']!=$info['team']){
            $this->error('该操作权限不够');
        }
    }
}